//
//  LGFollowOperationController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/6/27.
//

#import "LGFollowOperationController.h"
//手术列表
#import "LGFollowOperationView.h"
#import "DatePickerView.h"

#define topMargin  (Screen_H-bottomSafeBarHeight/3.0-viewPix(64))

@interface LGFollowOperationController ()<UITableViewDelegate,UITableViewDataSource>
/**   */
@property (nonatomic , strong)LGFollowOperationView *operationView;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *saveButton;
/**   */
@property (nonatomic , strong)UIButton *deleteBtn;
/**   */
@property (nonatomic , strong)NSArray *titleArray;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , strong)NSArray *codeArray;
/**   */
@property (nonatomic , copy)NSString *dateString;
/**   */
@property (nonatomic , copy)NSString *oldDate;
/**   */
@property (nonatomic , copy)NSString *surgeryStr;

@end

@implementation LGFollowOperationController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titleArray = @[@"手术时间",@"手术类型"];
    self.oldDate = (_oldDate && _oldDate.length>0)?_oldDate:@"";
    self.navigationView.title = (_dataDic && _dataDic.allKeys.count>0)?@"编辑手术史":@"添加手术史";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.saveButton];
    [[UIApplication sharedApplication].keyWindow addSubview:self.operationView];
    [self requestData];
    [self.tableView reloadData];
}

-(void)requestData{
    [RequestUtil withPOST:@"/api/common.dict/surgerysDict" parameters:@{} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.dataArray = returnData;
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    self.oldDate = LGNSString(dataDic[@"old_date"]);
    self.surgeryStr = LGNSString(dataDic[@"short_names"]);
    self.dateString = LGNSString(dataDic[@"date"]);
    self.codeArray = dataDic[@"codes"];
    [self.view addSubview:self.deleteBtn];
    [self.saveButton setTitle:@"保存" forState:UIControlStateNormal];
    self.saveButton.frame = CGRectMake(kMaxX(self.deleteBtn.frame)+viewPix(24), topMargin, (Screen_W-viewPix(118))/2.0, viewPix(48));
}


-(void)sendSelectDate:(NSString *)date index:(NSInteger)index{
    self.dateString = date;
}

//保存
-(void)saveButtonAction{
    if(self.dateString.length == 0){
        [TooltipView showMessage:@"请设置手术时间" offset:0];
        return;
    }
    
    if(self.surgeryStr.length == 0){
        [TooltipView showMessage:@"请选择手术名称" offset:0];
        return;
    }
    
    [RequestUtil withPOST:@"/doctor/patient.health_records/surgerySave" parameters:@{@"patient_id":self.patientid,@"surgery_date":self.dateString,@"old_date":self.oldDate,@"codes":self.codeArray} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshSurgeryData" object:nil userInfo:@{@"surgerys":returnData}];
            [TooltipView showMessage:@"保存成功" offset:0];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } error:^(NSError *error) {
        
    }];
}

//删除
-(void)deleteButtonAction{
    [RequestUtil withPOST:@"/doctor/patient.health_records/surgeryDelete" parameters:@{@"patient_id":self.patientid,@"ids":LGNSString(self.dataDic[@"ids"])} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RefreshSurgeryData" object:nil userInfo:@{@"surgerys":returnData}];
            [TooltipView showMessage:@"删除成功" offset:0];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:@"删除失败，请重试" offset:0];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGFollowOperationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.title = self.titleArray[indexPath.row];
    cell.content = (indexPath.row == 0)?self.dateString:self.surgeryStr;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    __weak typeof(self) weakSelf = self;
    if(indexPath.row == 0){
        //手术时间
        DatePickerView *pickerView = [[DatePickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
        pickerView.currentDate = self.dateString;
        pickerView.title = @"手术时间";
        [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
        pickerView.selectDate = ^(NSString *date) {
            weakSelf.dateString = date;
            [weakSelf.tableView reloadData];
        };
        
    }else{
        //手术类型
        LGFollowOperationView *operationView = [[LGFollowOperationView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
        operationView.dataArray = self.dataArray;
        operationView.codeArray = [NSMutableArray arrayWithArray:self.codeArray];
        [[UIApplication sharedApplication].keyWindow addSubview:operationView];
        operationView.selectOperationChanged = ^(NSArray * _Nonnull codeArray) {
            weakSelf.codeArray = codeArray;
            NSString *name = @"";
            for (NSDictionary *tempDic in weakSelf.dataArray) {
                NSString *code = LGNSString(tempDic[@"code"]);
                if([codeArray containsObject:code]){
                    name = (name.length>0)?[NSString stringWithFormat:@"%@+%@",name,tempDic[@"short"]]:tempDic[@"short"];
                }
            }
            weakSelf.surgeryStr = name;
            [weakSelf.tableView reloadData];
        };
    }
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topBarHeight, Screen_W, topMargin-topBarHeight) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGFollowOperationCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
    }
    return _tableView;
}

-(UIButton *)saveButton{
    if(!_saveButton){
        _saveButton = [UIButton buttonWithTitle:@"保存记录" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#FFFFFF" selectColor:@"#FFFFFF"];
        _saveButton.frame = CGRectMake(viewPix(16), topMargin, Screen_W-viewPix(32), viewPix(48));
        _saveButton.backgroundColor = [UIColor colorWithString:@"#429BFF"];
        _saveButton.cornerRidus = 10;
        [_saveButton addTarget:self action:@selector(saveButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveButton;
}

-(UIButton *)deleteBtn{
    if(!_deleteBtn){
        _deleteBtn = [UIButton buttonWithTitle:@"删除" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#DD3030" selectColor:@"#DD3030"];
        _deleteBtn.frame = CGRectMake(viewPix(47), topMargin, (Screen_W-viewPix(118))/2.0, viewPix(48));
        _deleteBtn.layer.borderColor = [UIColor colorWithString:@"#DD3030"].CGColor;
        _deleteBtn.layer.borderWidth = 1;
        _deleteBtn.cornerRidus = 10;
        [_deleteBtn addTarget:self action:@selector(deleteButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}



@end


@interface LGFollowOperationCell()
/**   */
@property (nonatomic , strong)UIView *baseView;
/**   */
@property (nonatomic , strong)UILabel *titleLabel;
/**   */
@property (nonatomic , strong)UILabel *contentLabel;
/**   */
@property (nonatomic , strong)UIImageView *tipView;

@end


@implementation  LGFollowOperationCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self createSubView];
    }
    return  self;
}

-(void)setTitle:(NSString *)title{
    _title = title;
    self.titleLabel.text = title;
}

-(void)setContent:(NSString *)content{
    _content = content;
    self.contentLabel.text = (content.length>0)?content:@"请选择";
    NSString *colorStr = (content.length>0)?@"#333333":@"#999999";
    self.contentLabel.textColor = [UIColor colorWithString:colorStr];
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.clipsToBounds = YES;
    self.backgroundColor = [UIColor clearColor];
    self.contentView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.baseView];
    [self.baseView addSubview:self.titleLabel];
    [self.baseView addSubview:self.contentLabel];
    [self.baseView addSubview:self.tipView];
    [self.baseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(viewPix(6));
        make.bottom.equalTo(self.contentView).offset(-viewPix(10));
        make.left.equalTo(self.contentView).offset(viewPix(16));
        make.right.equalTo(self.contentView).offset(-viewPix(16));
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.baseView).offset(viewPix(16));
        make.left.equalTo(self.baseView).offset(viewPix(12));
    }];
    
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.baseView).offset(viewPix(16));
        make.left.equalTo(self.baseView).offset(viewPix(88));
        make.right.equalTo(self.baseView).offset(-viewPix(28));
        make.bottom.equalTo(self.baseView).offset(-viewPix(16));
    }];
    [self.tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.baseView).offset(-viewPix(12));
        make.centerY.equalTo(self.baseView);
        make.width.height.equalTo(@(viewPix(12)));
    }];
    
}
-(UIView *)baseView{
    if(!_baseView){
        _baseView = [UIView shadowViewWithColor:@"#B2BDC7" offset:CGSizeMake(0, 2) opacity:0.15 radius:15];
        _baseView.backgroundColor = [UIColor whiteColor];
    }
    return _baseView;
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _titleLabel;
}


-(UILabel *)contentLabel{
    if(!_contentLabel){
        _contentLabel = [UILabel lableWithText:@"" colorString:@"#333333" textFont:LGFont(15) textAlignment:NSTextAlignmentRight lines:0];
    }
    return _contentLabel;
}

-(UIImageView *)tipView{
    if(!_tipView){
        _tipView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"grayTip12"]];
    }
    return _tipView;
}


@end
